package com.zhouchao.persistence.config;

import com.zhouchao.persistence.enums.SqlCommandType;
import com.zhouchao.persistence.pojo.Configuration;
import com.zhouchao.persistence.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: zhouchao
 * @Date: 2021/05/03 17:21
 * @Description:
 */
public class XMLMapperBuilder {

    private final Set<String> set = new HashSet<>(Arrays.asList("select|insert|update|delete".split("\\|")));

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseMapper(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> elementList = rootElement.elements();
        for (Element element : elementList) {

            String elementName = element.getName();

            // 如果不是select|insert|update|delete标签，直接跳过，其实这里应该是由约束头处理用户写错的标签
            if (!set.contains(elementName)) continue;

            String id = element.attributeValue("id");

            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();
            MappedStatement ms = new MappedStatement();
            ms.setId(id);
            ms.setResultType(resultType);
            ms.setParameterType(parameterType);
            ms.setSql(sql);
            ms.setType(SqlCommandType.getByCode(elementName));

            String key = namespace + "." + ms.getId();
            configuration.getMapperStatementMap().put(key, ms);
        }
    }
}
